<template>
  <div class="course-list">
    <div class="course-info-page">
      <el-row :gutter="20">
        <el-col :sm="24" :lg="24">
          <div class="course-info-header text-success" style="font-size: 14px; display: flex; justify-content: space-between; align-items: center;">
            <h1>我的授课</h1>
          </div>
          <hr />
        </el-col>
      </el-row>
    </div>
    <!-- 根据 isDataReady 标志位决定是否渲染课程列表 -->
    <el-row :gutter="20" v-if="isDataReady">
      <el-col :span="4" v-for="course in courseList" :key="course.courseId">
        <el-card>
          <template #header>
            <div class="card-header">
              <h3>{{ course.courseName }}</h3>
            </div>
          </template>
          <div class="card-content">
            <p><strong>课程 ID:</strong> {{ course.courseId }}</p>
            <p><strong>课程描述:</strong> {{ course.courseDescription }}</p>
            <p class="flex-row">
              <strong>课程时间:</strong>
              <dict-tag :options="dict.type.course_week" :value="course.courseWeek"/>
              <dict-tag :options="dict.type.course_sequence" :value="course.courseSequence"/>
            </p>
            <p><strong>教室:</strong> {{ course.classroom }}</p>
            <p><strong>开课日期:</strong> {{ course.startDate }}</p>
            <p><strong>结课日期:</strong> {{ course.endDate }}</p>
            <p class="flex-row">
              <strong>课程类型:</strong>
              <dict-tag :options="dict.type.course_type" :value="course.courseType"/>
            </p>
          </div>
          <div class="card-footer">
            <!-- 根据课程的 isStarted 状态显示不同的按钮 -->
            <el-button
              v-if="!activeCourseId || (activeCourseId === course.courseId)"
              :type="course.isStarted ? 'success' : 'primary'"
              :icon="course.isStarted ? 'el-icon-view' : 'el-icon-video-play'"
              @click="course.isStarted ? viewCourse(course.courseId, course.userId, course.courseName) : startCourse(course.courseId)"
            >
              {{ course.isStarted ? '查看详情' : '开始上课' }}
            </el-button>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getCourseList, getCourseStartStatus, addCourseRecord } from "@/api/course/startCourse"

export default {
  name: "StartCourse",
  dicts: ['course_hours', 'course_type', 'course_sequence', 'course_credit', 'course_week'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 课程列表
      courseList: [], // 初始化为空数组
      // 记录当前正在上课的课程 ID
      activeCourseId: null,
      // 数据是否准备好的标志位
      isDataReady: false
    };
  },
  created() {
    // 在组件创建完成后调用接口获取课程列表
    this.fetchCourseList();
  },
  methods: {
    fetchCourseList() {
      // 开始加载，显示加载状态
      this.loading = true;
      getCourseList().then(response => {
        // 为每个课程动态添加 isStarted 属性，并确保响应式
        this.courseList = response.data.map(course => {
          return {...course, isStarted: false };
        });
        // 为每个课程查询上课状态
        const promises = this.courseList.map(course => {

          return getCourseStartStatus(course.courseId).then(res => {
            course.isStarted = res.data;
            if (course.isStarted) { // 该课程已被选择
              // 记录当前正在上课的课程 ID
              this.activeCourseId = course.courseId;
            }
            return course;
          });
        });
        // 等待所有查询完成
        Promise.all(promises).then(() => {
          this.loading = false;
          // 数据准备好，设置标志位为 true
          this.isDataReady = true;
        });
      }).catch(error => {
        console.error('获取课程列表数据失败:', error);
        this.loading = false;
      });
    },
    startCourse(courseId) {
      addCourseRecord(courseId).then(() => {
        this.$modal.msgSuccess("开始上课...");
        this.fetchCourseList();
      }).catch(error => {
        // 错误处理交给请求拦截器，这里简单打印错误信息
        this.$modal.msgError('新增课程上课记录失败:', error);
      });
    },
    viewCourse(courseId, userId, courseName) {
      // 找到要查看详情的课程
      const course = this.courseList.find(c => c.courseId === courseId);
      if (course) { // 该课程已经开始上课
        this.$router.push({ // 跳转到课程信息页面并传递课程ID和教师ID
          path: '/startCourse/course-info',
          query: {
            courseId: courseId,
            userId: userId,
            courseName: courseName
          }
        });
      }
    }
  }
};
</script>

<style scoped>
.course-list {
  padding: 20px;
}

.card-header {
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  margin-bottom: 10px;
}

.card-content {
  margin-bottom: 20px;
}

.card-footer {
  text-align: center;
}

.flex-row {
  display: flex;
  align-items: center;
}

.flex-row strong {
  margin-right: 8px;
}

.course-info-page {
  padding: 20px;
}

.course-info-header {
  padding: 10px 20px;
  margin: 0 0 20px;
  border-left: 5px solid #eee;
}

.course-info-header h1 {
  margin: 0;
}
</style>
